package com.uziot.bucket.common.concurrent;

import java.util.concurrent.ForkJoinPool;

import java.util.concurrent.Future;

import java.util.concurrent.RecursiveTask;


/**
 * @author shidt
 * @version V1.0
 * @className ComplexCaculateTask
 * @date 2019-12-20 08:51:35
 * @description 有返回值的工作窃取算法
 */

public class RecursiveTaskDemo extends RecursiveTask<Integer> {

    private static final long serialVersionUID = -8979139704702284391L;

    /**
     * 任务拆分临界点
     */
    private static final Integer MAX_LIMIT = 3;

    private final Integer start;
    private final Integer end;

    public RecursiveTaskDemo(Integer start, Integer end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        //任务足够小（类似递归）
        if (end - start <= MAX_LIMIT) {
            for (int i = start; i <= end; i++) {
                sum = sum + i;
            }
        } else {
            //任务一分为2
            int middle = (end + start) / 2;
            RecursiveTaskDemo leftTask = new RecursiveTaskDemo(start, middle);
            RecursiveTaskDemo rightTask = new RecursiveTaskDemo(middle + 1, end);

            //执行任务
            leftTask.fork();
            rightTask.fork();

            //汇总各个分任务节点
            Integer leftResult = leftTask.join();
            Integer rightResult = rightTask.join();
            sum = leftResult + rightResult;
        }
        return sum;
    }

    public static void main(String[] args) {
        ForkJoinPool forkjoinPool = new ForkJoinPool();

        //生成一个计算任务
        RecursiveTaskDemo task = new RecursiveTaskDemo(1, 100);

        //执行一个任务 （这个是有等待返回的调用方式）
        Future<Integer> result = forkjoinPool.submit(task);
        try {
            System.out.println(result.get());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            forkjoinPool.shutdown();
        }

    }
}